<template>
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body v-drag-fullscreen>
    <el-form :inline="true" :model="queryParams" ref="queryForm" size="small" label-width="0" class="demo-form-inline"
             style="height: 40px;float: right;">
      <el-form-item prop="billUser">
        <el-input
          v-model="queryParams.billUser"
          placeholder="收款人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item style="width: 100px;" prop="chargeId">
        <el-select v-model="queryParams.chargeId" placeholder="收费项目" clearable size="small">
          <el-option
            v-for="dict in itemOptions"
            :key="dict.chargeId"
            :label="dict.chargeName"
            :value="dict.chargeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="billTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="收款日期开始"
          end-placeholder="收款日期结束">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"></el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"></el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="listData"
      @selection-change="handleSelectionChange"
      :header-cell-style="styleTitleFunc"
      height="300"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="收款单号" align="center" prop="receiptNo" width="120"/>
      <el-table-column label="收款日期" align="center" prop="billDate" width="100"/>
      <el-table-column label="收款人" align="center" prop="billUser" width="100"/>
      <el-table-column label="客户名称" align="center" prop="customName" width="100"/>
      <el-table-column label="收费项目" align="center" prop="chargeName"/>
      <el-table-column label="收费标准" v-if="modelType != 'baozhengjin'" align="center" prop="normNames"/>
      <el-table-column label="计费开始时间" v-if="modelType != 'baozhengjin'" align="center" prop="beginTime" width="120"/>
      <el-table-column label="计费结束时间" v-if="modelType != 'baozhengjin'" align="center" prop="finishTime" width="120"/>
      <el-table-column label="实收金额" align="center" prop="billMoney" width="100"/>
      <el-table-column label="可退金额" align="center" prop="refundAmount" width="100"/>
      <el-table-column label="退款金额" align="center" prop="drawbackMoney" width="100">
        <template slot-scope="scope">
          <el-input class="special_money_class" @change="(v)=>changeRefundAmount(scope.row,v)" v-model="scope.row.drawbackMoney"></el-input>
        </template>
      </el-table-column>
      <el-table-column v-if="modelType == 'baozhengjin'" label="转存金额" align="center" prop="transferAmount" width="100">
        <template slot-scope="scope">
          <el-input class="special_money_class" @change="(v)=>changeRefundAmount(scope.row,v)" v-model="scope.row.transferAmount"></el-input>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-form class="bottomForm" :model="form" ref="form" size="mini" label-position="left" label-width="65px">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="付款人" prop="paymentUserName" >
            <el-input  v-model="form.paymentUserName"  readonly />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="付款日期" prop="paymentTime" >
            <el-date-picker
              v-model="form.paymentTime"
              type="date"
              value-format="yyyy-MM-dd"
              prefix-icon="node"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="退款金额" prop="paymentMoney" >
            <el-input  v-model="form.paymentMoney"  readonly placeholder="请输入收到金额"/>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="modelType == 'baozhengjin'">
          <el-form-item label="转存金额" prop="transferAmount" >
            <el-input  v-model="form.transferAmount" readonly placeholder="请输入收到金额"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="打印模板" prop="printTemplate" >
            <el-select v-model="form.printTemplate" clearable placeholder="请选择打印模板">
              <el-option
                v-for="item in printTempletOptions"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" v-hasPermi="['payfee:advicePayment:add']">退 费</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <advice-payment ref="adviceRefs" @ok="createAdviceReceipt" :modelType="modelType"/>

  </el-dialog>
</template>

<script>
  //已收款列表
  import {getTooReceiptlist,addAdvicePayment} from "@/api/payfee/advicePayment";
  import {listMixin} from "@/utils/mixins/listMixin";
  import { listItem } from "@/api/payfee/item";
  import { listPrintTemplet } from "@/api/system/printTemplet";
  import AdvicePayment from "./advicePayment";

  export default {
    name: "tooReceiptlist",
    components:{ AdvicePayment },
    mixins: [listMixin],
    props: {
      modelType: {
        type: String,
      },
      projectIdIN: {
        type: String,
        default: '-1'
      },
    },
    data() {
      return {
        open: false,
        title: "已收款列表",
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          roomId:null,
          chargeId:null,//收费项目ID
          billUser:null,// 收款人
          params:{}
        },
        //已收款列表数据
        listData: [],
        //收费项目字典
        itemOptions:[],
        //收款日期
        billTime:[],
        //选中列表
        selection:[],
        currentNode:{},
        printTempletOptions:[],
        form:{}
      }
    },
    created() {
      listItem({projectId:'03'}).then(res=>{
        this.itemOptions = res.rows;
      })
    },
    methods: {
      show(option) {
        this.reset()
        this.getListPrintTemplet()
        this.currentNode = option.currentNode
        this.getList()
        this.open = true
      },
      getList() {
        this.loading = true;
        this.queryParams.params.projectIdIN = this.projectIdIN
        this.queryParams.roomId =  this.currentNode.id
        let queryParams = this.addDateRange(this.queryParams,this.billTime,"billTime")
        getTooReceiptlist(queryParams).then(response => {
          this.listData = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.billTime = []
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.selection = selection
        this.computeOutlay()
      },
      changeRefundAmount(row,v){
        //退款金额+转存金额
        let money = this.$utils.add(row.drawbackMoney,row.transferAmount)
        if(money > row.refundAmount){
          row.drawbackMoney = row.refundAmount
          row.transferAmount = 0
          this.msgWarning("退款金额不能超出可退款金额")
        }
        this.computeOutlay()
      },
      computeOutlay(){
        let paymentMoney = 0;
        let transferAmount = 0;
        this.listData.forEach((row) => {
          let index = this.selection.findIndex(x=>row.receiptNo==x.receiptNo)
          if(index != -1){
            paymentMoney = this.$utils.add(paymentMoney,Number(row.drawbackMoney))
            transferAmount = this.$utils.add(transferAmount,Number(row.transferAmount))
          }
        })
        this.form.paymentMoney = paymentMoney
        this.form.transferAmount = transferAmount
      },
      cancel(){
        this.open = false
      },
      submitForm(){
        let me = this
        if(!this.selection.length){
          this.msgWarning("请选择需要退款的收款明细列表")
          return false
        }
        let errorlist = this.selection.filter(row=> !row.relevancePayable)
        if(errorlist.length > 0){
          let nos = errorlist.map(item => item.receiptNo)
          this.$confirm(`收款单[${nos}]对应收费项目没有维护付款项目,请前往收费管理->收费参数->收费项目维护对应应付`, "警告", {
            confirmButtonText: "前往",
            cancelButtonText: "取消",
            dangerouslyUseHTMLString:true,
            type: "warning"
          }).then(function() {
            me.$router.push({ path: "/payfee/costParameters",query:{activeName:'sfxm'} })
          }).catch(() => {});
          return false;
        }
        this.$refs.adviceRefs.show({ adviceForm:this.form })
      },
      styleTitleFunc({row,column,rowIndex, columnIndex}){
        if(column.property=='drawbackMoney' || column.property=='transferAmount'){
          return "color: red;"
        }
      },
      changeDrawbackMoney(row,v){
        if(v > row.refundAmount){
          row.drawbackMoney = row.refundAmount
          this.msgWarning("退款金额不能超出可退款金额")
        }
      },
      //打印模板字典
      getListPrintTemplet(){
        listPrintTemplet({templetType: '10',status:'0'}).then(res=>{
          this.printTempletOptions = res.rows
        })
      },
      reset() {
        this.selection = []
        this.form = {
          paymentMoney:0,
          transferAmount:0,
          paymentTime: this.parseTime(new Date(),'{y}-{m}-{d}'),
          printTemplate: null,
          paymentUserName: this.$store.state.user.nickName,
          modePayments: [
            {
              collectionMethod: '10001',//收款方式
              billMoney: 0//收款金额
            }
          ]
        }
        this.resetForm("form");
      },
      //创建付款单
      createAdviceReceipt(param){
        let params = {
          roomId:this.currentNode.id,
          businessType:'RECEIPT',
          paymentMoney:param.paymentMoney,
          transferAmount:param.transferAmount,
          tooReceiptVos:this.selection,
          modePayments: param.modePayments
        }
        addAdvicePayment(params).then(res=>{
          this.open = false
          this.$emit("ok")
        })
      }

    }
  }
</script>


<style lang="scss" scoped>
  .submit-but{
    text-align: center;
    .link-but{
      margin-left: 10px;
    }
  }

  .operate-but{
    text-align: center;
  }
  ::v-deep .bottomForm{
    margin-top: 20px;
    .el-input__inner{
      border: none;
      border-bottom:1px solid #DCDFE6;
      border-radius: 0;
      padding: 0 5px;
    }
    .el-form-item--mini .el-form-item__label{
      padding: 3px !important;
    }
    .el-input-group__append, .el-input-group__prepend{
      border: none;
      background: none;
      font-weight: bold;
      font-size: 14px;
    }
  }

  ::v-deep .el-table__row{
    .el-input__inner{
      border: none;
      border-bottom: 1px solid #DCDFE6;
      border-radius: 0;
      padding: 0 5px;
    }
  }
  ::v-deep .topForm{
    .el-input__inner{
      border: none;
      border-bottom:1px solid #DCDFE6;
      border-radius: 0;
      padding: 0 5px;
    }
  }
</style>
